package com.nerve.android.cloudoffice.app.activity.customer;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;
import org.nerve.android.ui.dialog.DialogHelper.ConfirmListener;
import org.nerve.android.ui.dialog.SpinnerDialog;
import org.nerve.util.DateUtil;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.activity.assist.UserSelectActivity;
import com.nerve.android.cloudoffice.app.activity.department.AddUserActivity;
import com.nerve.android.cloudoffice.app.activity.task.AddTaskActivity;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.common.Resource;
import com.nerve.android.cloudoffice.domain.Customer;
import com.nerve.android.cloudoffice.service.data.CustomerData;

@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.activity_customer_add)
public class AddCustomerActivity extends NavigationActivity implements OnClickListener, ConfirmListener{

	public static final String CUSTOMER = "CUSTOMER";
	
	private static final int CATEGORY = 0;
	private static final int PROJECT_TYPE = 1;
	
	@ViewOnId(id=R.id.worker, clickListener="this")
	private EditText workerET;
	@ViewOnId(id=R.id.projectPlace)
	private EditText addressET;
	@ViewOnId(id=R.id.projectType, clickListener="this")
	private EditText projectTypeET;
	@ViewOnId(id=R.id.category, clickListener="this")
	private EditText categoryET;
	@ViewOnId(id=R.id.workGroup)
	private RadioGroup workTypeGroup;
	@ViewOnId(id=R.id.radio_chengbao)
	private RadioButton chengbaoRadio;
	@ViewOnId(id=R.id.radio_buy)
	private RadioButton buyRadio;
	@ViewOnId(id=R.id.startDate, clickListener="this")
	private EditText startDateET;
	@ViewOnId(id=R.id.cycle)
	private EditText cycleET;
	@ViewOnId(id=R.id.foundation)
	private EditText foundationET;
	@ViewOnId(id=R.id.username)
	private EditText usernameET;
	@ViewOnId(id=R.id.phone)
	private EditText phoneET;
	@ViewOnId(id=R.id.qq)
	private EditText qqET;
	@ViewOnId(id=R.id.price)
	private EditText priceET;
	@ViewOnId(id=R.id.time1)
	private EditText time1ET;
	@ViewOnId(id=R.id.time2)
	private EditText time2ET;
	@ViewOnId(id=R.id.time3)
	private EditText time3ET;
	@ViewOnId(id=R.id.time4)
	private EditText time4ET;
	@ViewOnId(id=R.id.remark)
	private EditText remarkET;

	private SpinnerDialog projectSpinnerDialog;
	private SpinnerDialog categorySpinnerDialog;
	
	private Customer customer;
	private int projectType;
	private int category;
	
	private int workerId;//保存了接受人id
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			hideProgressDialog();
			switch (msg.what) {
			case WORKER_FAIL:
				toast(Const.ERROR);
				break;
				
			case WORKER_OK:
				toast("保存成功");
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		super.initUI();
		
		setNavTitle(customer == null?"新增单子" : "查看单子");
		customNavigateRightButton("保存", true);
		
		showCustomer();
	}
	
	@Override
	protected void initData() {
		Object obj = getData(CUSTOMER, true);
		
		if(obj != null && obj instanceof Customer){
			customer = (Customer)obj;
			
			category = customer.getCategory();
		}else{
			customer = new Customer();
			customer.setId(0);
		}
		
		workerId = OfficeApplication.getLoginId();
	}
	
	private void showCustomer(){
		if(customer == null){
			projectTypeET.setText(
					Resource.Customer.PROJECT_TYPE[projectType]
					);
			categoryET.setText(
					Resource.Customer.CATEGORY[category]
					);
			
			return ;
		}
		
		addressET.setText(customer.getAddress());
		projectTypeET.setText(
				Resource.Customer.PROJECT_TYPE[customer.getProjectType()]
				);
		if(customer.getWorkType() == Customer.WORK_SHI_GONG_FANG){
			chengbaoRadio.setChecked(true);
			buyRadio.setChecked(false);
		}else{
			chengbaoRadio.setChecked(false);
			buyRadio.setChecked(true);
		}
		
		if(customer.getStartDate() != null){
			startDateET.setText(
					DateUtil.toString(customer.getStartDate(), "yyyy-MM-dd")
					);
		}
		
		cycleET.setText(customer.getCycle()+"");
		usernameET.setText(customer.getName());
		workerET.setText(customer.getUser());
		phoneET.setText(customer.getPhone());
		qqET.setText(customer.getQq());
		priceET.setText(customer.getPrice() + "");
		time1ET.setText(customer.getTime1());
		time2ET.setText(customer.getTime2());
		time3ET.setText(customer.getTime3());
		time4ET.setText(customer.getTime4());
		remarkET.setText(customer.getRemark());
		foundationET.setText(customer.getFoundation());
		categoryET.setText(
				Resource.Customer.CATEGORY[customer.getCategory()]
				);
		
		projectType = customer.getProjectType();
	}

	@Override
	public void onClick(View v) {
		Const.log("点击了！！！！！！！！！！！！！！！！！！！");
		switch (v.getId()) {
		case R.id.worker:
			Intent intent = new Intent(this, UserSelectActivity.class);
			startActivityForResult(intent, AddTaskActivity.SELEC_USER);
			break;
		case R.id.projectType:
			if(projectSpinnerDialog == null){
				projectSpinnerDialog = new SpinnerDialog(this, Resource.Customer.PROJECT_TYPE);
				projectSpinnerDialog.setCode(PROJECT_TYPE);
				projectSpinnerDialog.setTitle("选择项目类型");
				projectSpinnerDialog.setConfirmListener(this);
			}
			projectSpinnerDialog.show();
			break;
			
		case R.id.category:
			if(categorySpinnerDialog == null){
				categorySpinnerDialog = new SpinnerDialog(this, Resource.Customer.CATEGORY);
				categorySpinnerDialog.setCode(CATEGORY);
				categorySpinnerDialog.setTitle("选择项目级别");
				categorySpinnerDialog.setConfirmListener(this);
			}
			categorySpinnerDialog.show();
			break;
			
		case R.id.startDate:
			showDialog(AddUserActivity.DATE_DIALOG);
			break;
		default:
			break;
		}
	}

	/**
     * 创建日期选择对话框
     */
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
		switch (id) {
		case AddUserActivity.DATE_DIALOG:
			Calendar calendar = Calendar.getInstance();
			dialog = new DatePickerDialog(
					this,
					new DatePickerDialog.OnDateSetListener() {
						public void onDateSet(DatePicker dp, int year,
								int month, int dayOfMonth) {
							
							//设置日期
							startDateET.setText( year + "-" + (month + 1) + "-"
									+ dayOfMonth);
						}
					}, 
					calendar.get(Calendar.YEAR), // 传入年份
					calendar.get(Calendar.MONTH), // 传入月份
					calendar.get(Calendar.DAY_OF_MONTH) // 传入天数
			);
			dialog.setTitle("选择日期");
			break;
		}
		return dialog;
    }
	
	@Override
	public void onConfirmClick(int position, Object obj) {
		if((Integer)obj == PROJECT_TYPE){
			projectType = position;
			
			projectTypeET.setText(
					Resource.Customer.PROJECT_TYPE[position]
					);
		}
		else{
			category = position;
			categoryET.setText(Resource.Customer.CATEGORY[position]);
		}
	}
	
	@Override
	protected void onNavigateBackButtonClick() {
		finish();
	}
	
	@Override
	protected void onNavigateRightButtonClick() {
		if(isEmpty(addressET)){
			toast("项目地址不能为空！");
			return ;
		}
		
		if(isEmpty(cycleET)){
			toast("项目周期不能为空！");
			return;
		}
		
		if(isEmpty(priceET)){
			toast("底价填写不正确");
			return ;
		}
		
		customer.setWorkType(
				workTypeGroup.getCheckedRadioButtonId() == R.id.radio_chengbao? 
						Customer.WORK_SHI_GONG_FANG
						: 
						Customer.WORK_MAI_CAI_LIAO
				);
		
		customer.setProjectType(projectType);
		customer.setCategory(category);
		
		customer.setPhone(phoneET.getText().toString());
		customer.setPrice(Integer.valueOf(getText(priceET)));
		customer.setFoundation(foundationET.getText().toString());
		customer.setAddress(getText(addressET));
		customer.setCycle(Integer.valueOf(getText(cycleET)));
		customer.setRemark(getText(remarkET));
		customer.setQq(getText(qqET));
		customer.setTime1(getText(time1ET));
		customer.setTime2(getText(time2ET));
		customer.setTime3(getText(time3ET));
		customer.setTime4(getText(time4ET));
		customer.setName(usernameET.getText().toString());
		
		customer.setUser(workerId + "");
		
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			customer.setStartDate(sdf.parse(startDateET.getText().toString()));
		}catch(Exception e){
		}
		
		new AddCustomerWorker().execute();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null)
			return ;
		
		if(requestCode == AddTaskActivity.SELEC_USER){
			String info = data.getStringExtra(UserSelectActivity.INFO);
			int id = data.getIntExtra(UserSelectActivity.ID, -1);
			
			if(id > 0){
				workerET.setText(info);
				workerId = id;
			}
		}
	}
	
	private class AddCustomerWorker extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {
			Reply re = CustomerData.save(customer);
			
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return WORKER_FAIL;
			}
			
			return WORKER_OK;
		}
			
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
	}
}